<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="700px" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./notice.data"
  import { saveOrUpdate } from "./notice.api"
  // 声明Emits
  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    labelWidth: 90,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      await setFieldsValue({ ...data.record })
    }
  })
  const title = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))
  async function handleSubmit(v) {
    try {
      let values = await validate()
      setModalProps({ confirmLoading: true })
      values.userIds += ","
      await saveOrUpdate(values, isUpdate.value)
      closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
